package ratelimit

import (
	"JK-Junior-Go-Engineer-Camp/webook/internal/service/sms"
	"JK-Junior-Go-Engineer-Camp/webook/pkg/limiter"
	"context"
	"errors"
)

var errLimited = errors.New("触发限流")

// RateLimitSMSService 短息服务的限流装饰器
type RateLimitSMSService struct {
	svc     sms.Service     // 被装饰的
	limiter limiter.Limiter // 限流器
	key     string          // 限流器的key
}

func NewRateLimitSMSService(svc sms.Service, l limiter.Limiter) *RateLimitSMSService {
	return &RateLimitSMSService{
		svc:     svc,
		limiter: l,
		key:     "sms-limiter",
	}
}

func (r *RateLimitSMSService) Send(ctx context.Context,
	templateId string, args []string, number ...string) error {
	// 加特性
	limited, err := r.limiter.Limit(ctx, r.key)
	if err != nil {
		return err
	}
	if limited { // 限流了
		return errLimited
	}
	// 将最终的逻辑委托给了被装饰的人
	return r.svc.Send(ctx, templateId, args, number...)
}
